package com.yuyou.weixin.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.validator.constraints.NotBlank;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;

/**
 * Created by wens on 2017/3/30.
 */
@Api(value="QRCodeController",description="获取二维码接口")
@Validated
@Controller
@RequestMapping("/api/qrcode")
public class QRCodeController {

	@ApiOperation(value="获取二维码")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "content", value = "内容", paramType="query", required = true)
    })
    @RequestMapping(value ="/encode",method = {RequestMethod.GET, RequestMethod.POST})
    public void encode(@NotBlank (message="content不能为空") String content, HttpServletResponse response) throws WriterException, IOException {
        content = URLDecoder.decode(content,"utf-8");
        int width = 300;
        int height = 300;
        //二维码的图片格式
        String format = "png";
        Map<EncodeHintType, String> hints = new HashMap<>();
        //内容所使用编码
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content,
                BarcodeFormat.QR_CODE, width, height, hints);
        BufferedImage image = toBufferedImage(bitMatrix);
        response.setContentType("image/png");
        ImageIO.write(image, format, response.getOutputStream());
    }

    private static BufferedImage toBufferedImage(BitMatrix matrix) {
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, matrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
            }
        }
        return image;
    }

}
